Explain the concept of functional interfaces with examples in Java.
Explain the concept of functional interfaces with examples in Java.
616
19-Jul-2024
Updated on 19-Jul-2024
Ashutosh Kumar Verma
19-Jul-2024Functional Interface in Java
A function interface is an interface with exactly one abstract method. Function interfaces are used extensively in lambda expressions and method statements to assign values in contexts that can be efficiently implemented. They form the basis for programming features introduced in Java 8 and later.
Characteristics of Functional Interfaces
Single Abstract Method (SAM) Function interfaces have exactly one abstract method that requires a lambda expression or method reference.
Default and static methods Functional interfaces can have default methods (methods with default implementations) and static methods (utility methods).
Annotation
@FunctionalInterface
Although not mandatory, annotating an interface with@FunctionalInterface
clearly indicates that it is intended to be used as a functional interface If the interface does not meet the requirements of a functional interface, the compiler issues an error they.Functional Interfaces Examples
Runnable It represents a task that can be executed concurrently.
Comparator It is used for comparing two objects of a specified type.
Supplier It provides a single value of a specified type.
Function It represents a function that accepts one argument and produces a result.
Consumer It represents an operation that accepts a single input argument and returns no result.
Example-
Usage of the lambda expression with the functional interface.
Output-
Benefits of Functional Interfaces
Concise code- Lambda expressions provide a concise way to implement methods defined through functional interfaces.
Readability- The code is made readable by focusing on what needs to be done rather than how.
Compatibility with Functional Programming- Java support for functional interfaces facilitates a highly responsive programming style, which is useful for tasks such as iterating over collections, parallel processing, event handling, and more
The functional interface in Java provides for the use of lambda expressions to represent abbreviated anonymous functions. They are a starting point for effective implementation of programming concepts in Java.
Also, Read: What are lambda expressions in Java, and how are they used?